package cn.geminis.data.jpa.graphql.fetcher;

import cn.geminis.data.jpa.GeminiRepository;
import cn.geminis.data.jpa.graphql.utils.QueryParametersUtils;
import graphql.schema.DataFetcher;
import graphql.schema.DataFetchingEnvironment;

import javax.persistence.EntityManager;
import javax.persistence.metamodel.EntityType;
import java.util.LinkedHashMap;

/**
 * @author puddi
 */
public class JpaDataFetcher implements DataFetcher {

    protected EntityManager entityManager;
    protected GeminiRepository geminiRepository;
    protected EntityType<?> entityType;

    public JpaDataFetcher(EntityManager entityManager, GeminiRepository geminiRepository, EntityType<?> entityType) {
        this.entityManager = entityManager;
        this.geminiRepository = geminiRepository;
        this.entityType = entityType;
    }

    @Override
    public Object get(DataFetchingEnvironment environment) {
        var field = environment.getField();

        var queryParameters = QueryParametersUtils.getQueryParameters(field);
        var type = this.entityType.getJavaType();
        var pagedData = this.geminiRepository.findPage(type, queryParameters);

        var result = new LinkedHashMap<>();
        result.put("totalElements", pagedData.getTotalElements());
        result.put("totalPages", pagedData.getTotalPages());
        result.put("content", pagedData.getContent());

        return result;
    }
}
